package com.plugin.seed.mybatis.defaultvalue.interceptor;

import com.plugin.seed.mybatis.defaultvalue.util.DefaultValueUtil;
import com.seed.pagehelper.PageData;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.util.List;

/**
 * @author Peter Fan
 */
@Intercepts({
        @Signature(
                type = Executor.class,
                method = "query",
                args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(
                type = Executor.class,
                method = "query",
                args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class})
})
public class ColumnDefaultValueQueryInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object result = invocation.proceed();
        if (result != null && result instanceof List) {
            List<?> list = (List<?>) result;
            if (list.isEmpty()) {
                return result;
            } else if (list.size() == 1 && list.get(0) instanceof PageData) {
                PageData<?> pageData = (PageData<?>) list.get(0);
                pageData.getList().forEach(DefaultValueUtil::cleanDefaultValue);
            } else {
                list.forEach(DefaultValueUtil::cleanDefaultValue);
            }

        }
        return result;
    }

}
